package com.xiguaji.tiktok.v1.ins.media.service;

import cn.hutool.core.date.DateUtil;
import com.xiguaji.boot.toolkit.elasticsearch.RestClientHelper;
import com.xiguaji.boot.toolkit.jdbc.Page;
import com.xiguaji.tiktok.config.Config;
import com.xiguaji.tiktok.utils.ESUtil;
import com.xiguaji.tiktok.v1.ins.blogger.dto.InsBloggerCfsData;
import com.xiguaji.tiktok.v1.ins.blogger.model.InsBlogger;
import com.xiguaji.tiktok.v1.ins.blogger.repository.InsBloggerRepository;
import com.xiguaji.tiktok.v1.ins.config.InsConfig;
import com.xiguaji.tiktok.v1.ins.media.dto.*;
import com.xiguaji.tiktok.v1.ins.media.model.InsMedia;
import com.xiguaji.tiktok.v1.ins.media.repository.InsMediaRepository;
import com.xiguaji.tiktok.v1.ins.media.repository.InsRelMediaTaggerUserRepository;
import lombok.val;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;


/**
 * 帖子相关服务
 * @author Huangxin
 */
@Service
public class InsMediaService {

    /**
     * insMediaRepository
     */
    @Autowired
    InsMediaRepository insMediaRepository;

    @Autowired
    InsBloggerRepository insBloggerRepository;

    @Autowired
    InsRelMediaTaggerUserRepository insRelMediaTaggerUserRepository;
    /**
     * insConfig
     */
    @Autowired
    InsConfig insConfig;

    @Autowired
    Config config;

    private final int [] TIMES = new int[]{6,12,24,24*3,24*7,24*15,24*30};
    private final int [] DAY_TYPE = new int[]{7,15,30};

    private final int HOUR_SECOND = 60*60;
    private final int MEDIA_TOTAL_SIZE = 500;


    /**
     * 分页
     * @param insAdMediaSearchRequest
     * @return
     */
    public Page<InsMediaData> findByPage(InsMediaSearchRequest insAdMediaSearchRequest){
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        boolQueryBuilder.must(QueryBuilders.rangeQuery("takenTime").gte(DateUtil.offsetDay(new Date(),-config.getLatestDays()).getTime()/1000));
        // 帖子类型（1广告帖2非广告帖）
        if(insAdMediaSearchRequest.getMediaAdType() > 0){
            boolQueryBuilder.must(QueryBuilders.matchQuery("isAd",insAdMediaSearchRequest.getMediaAdType()));
        }

        // 分类
        if(!StringUtils.isEmpty(insAdMediaSearchRequest.getCategory())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("bloggerOverallCategoryName",insAdMediaSearchRequest.getCategory()));
        }

        if(!StringUtils.isEmpty(insAdMediaSearchRequest.getTitle())){
            boolQueryBuilder.must(QueryBuilders.wildcardQuery("caption",insAdMediaSearchRequest.getTitle().toLowerCase()+"*"));
        }

        // 是否视频帖
        switch (insAdMediaSearchRequest.getType()){
            case 1:
                boolQueryBuilder.must(QueryBuilders.matchQuery("isVideo",false));
                break;
            case 2:
                boolQueryBuilder.must(QueryBuilders.matchQuery("productType","feed"));
                boolQueryBuilder.must(QueryBuilders.matchQuery("isVideo",true));
                break;
            case 3:
                boolQueryBuilder.must(QueryBuilders.matchQuery("productType","clips"));
                boolQueryBuilder.must(QueryBuilders.matchQuery("isVideo",true));
                break;
            case 4:
                boolQueryBuilder.must(QueryBuilders.matchQuery("productType","igtv"));
                boolQueryBuilder.must(QueryBuilders.matchQuery("isVideo",true));
                break;
            default:
                break;
        }

        // 是否赞助帖
        if(insAdMediaSearchRequest.getSponsored() > 0){
            if(insAdMediaSearchRequest.getSponsored() == 1){
                boolQueryBuilder.must(QueryBuilders.matchQuery("isSponsored",true));
            }else {
                boolQueryBuilder.must(QueryBuilders.matchQuery("isSponsored",false));
            }
        }

        // 标记帐户搜索
        if(!StringUtils.isEmpty(insAdMediaSearchRequest.getTaggedUsername())){
            boolQueryBuilder.must(QueryBuilders.nestedQuery("taggedBloggers",QueryBuilders.matchQuery("taggedBloggers.username",insAdMediaSearchRequest.getTaggedUsername()), ScoreMode.Total));
        }

        // 标记帐户类型
        switch (insAdMediaSearchRequest.getTaggedAccount()){
            case 1:
                boolQueryBuilder.must(QueryBuilders.nestedQuery("taggedBloggers",QueryBuilders.existsQuery("taggedBloggers.uid"),ScoreMode.Total));
                break;
            case 2:
                boolQueryBuilder.must(QueryBuilders.nestedQuery("taggedBloggers",QueryBuilders.matchQuery("taggedBloggers.business",true),ScoreMode.Total));
                break;
            case 3:
                boolQueryBuilder.must(QueryBuilders.nestedQuery("taggedBloggers",QueryBuilders.matchQuery("taggedBloggers.business",false),ScoreMode.Total));
                break;
            default:
                break;
        }

        // 标记商品的类型
        switch (insAdMediaSearchRequest.getTaggedProduct()){
            case 1:
                boolQueryBuilder.mustNot(QueryBuilders.matchQuery("productTagType",0));
                break;
            case 2:
                boolQueryBuilder.must(QueryBuilders.matchQuery("productTagType",1));
                break;
            case 3:
                boolQueryBuilder.must(QueryBuilders.matchQuery("productTagType",2));
                break;
            default:
                break;
        }

        // 发帖时间
        if(insAdMediaSearchRequest.getPostingTime() > 0){
            int index = insAdMediaSearchRequest.getPostingTime() -1;
            int endTime = (int) (System.currentTimeMillis()/1000 - HOUR_SECOND*TIMES[index]);
            boolQueryBuilder.must(QueryBuilders.rangeQuery("takenTime").gte(endTime));
        }

        //排序
        String sort;
        switch (insAdMediaSearchRequest.getSort()){
            case 0:
                sort = "videoViewCount";
                break;
            case 1:
                sort = "likeCount";
                break;
            case 2:
                sort = "commentCount";
                break;
            case 4:
                sort = "score";
                break;
            default:
                sort = "er";
                break;
        }
        Page<InsMediaData>  page = RestClientHelper.page(InsMediaData.class, ESUtil.INS_MEDIA_INDEX,boolQueryBuilder,insAdMediaSearchRequest.getPage(),insAdMediaSearchRequest.getPageSize(),MEDIA_TOTAL_SIZE,sort, SortOrder.DESC);
        page.getList().forEach(insAdMediaListData -> {
            Optional<InsBlogger> insBloggerOptional = insBloggerRepository.findByUid(insAdMediaListData.getOwnerUid());
            if(insBloggerOptional.isPresent()){
                insAdMediaListData.setUsername(insBloggerOptional.get().getUsername());
                insAdMediaListData.setFullName(insBloggerOptional.get().getFullName());
                insAdMediaListData.setBloggerPic(insBloggerOptional.get().getPicUrl());
                insAdMediaListData.setIsVerified(insBloggerOptional.get().getIsVerified());
            }
        });
        return page;
    }

    /**
     * 获取作品详细信息
     * @param id
     * @return
     */
    /*public InsMediaDetail insMediaById(long id){
        // 作品基本信息
        InsMediaDetail insMediaDetail = RestClientHelper.findById(InsMediaDetail.class,ESUtil.INS_MEDIA_INDEX,String.valueOf(id));
        insMediaDetail.getTaggedBloggers().forEach( t-> {
            Optional<InsBlogger> insBlogger = insBloggerRepository.findByUid(t.getUid());
            if(insBlogger.isPresent()){
                t.setPicUrl(insBlogger.get().getPicUrl());
            }
        });

        // 时间区间
        long timeRang = System.currentTimeMillis() / 1000 - insConfig.getLatestDays() * 24 * 3600;
        // 博主信息
        InsAdBloggerInfo insAdBloggerInfo = insMediaRepository.findInsAdBloggerInfoByUid(insMediaDetail.getOwnerUid(),timeRang);
        insMediaDetail.setInsBloggerInfo(insAdBloggerInfo);

        //标签
        insMediaDetail.setTags(insMediaRepository.findInsMediaTags(id));

        // 作品百分比
        InsMediaInfoRate insMediaInfoRate = new InsMediaInfoRate();
        insMediaInfoRate.setLikeRate(insMediaDetail.getLikeCount()/(insAdBloggerInfo.getFollowerCount()+0.0));
        insMediaInfoRate.setReviewRate(insMediaDetail.getCommentCount()/(insAdBloggerInfo.getFollowerCount()+0.0));
        insMediaInfoRate.setViewRate(insMediaDetail.getVideoViewCount()/(insAdBloggerInfo.getFollowerCount()+0.0));
        insMediaInfoRate.setEr(insMediaDetail.getEr());
        insMediaDetail.setPostPerformance(insMediaInfoRate);

        // 同量级
        InsMediaInfoRate levePostPerformance = insMediaRepository.findInsMediaInfoRateByLevel(insAdBloggerInfo.getFollowerCount(),insAdBloggerInfo.getOverallCategoryName());
        insMediaDetail.setLevelPostPerformance(levePostPerformance);

        return insMediaDetail;
    }*/
    public InsMediaDetail insMediaById(long id){
        // 作品基本信息
        InsMedia insMedia = insMediaRepository.findById(id);
        InsMediaDetail insMediaDetail = new InsMediaDetail();

        if(null != insMedia){
            insMediaDetail = new InsMediaDetail();
            insMediaDetail.setId(insMedia.getId());
            insMediaDetail.setOwnerUid(insMedia.getOwnerUid());
            insMediaDetail.setShortcode(insMedia.getShortcode());
            insMediaDetail.setDisplayUrl(insMedia.getDisplayUrl());
            insMediaDetail.setIsVideo(insMedia.getIsVideo());
            insMediaDetail.setIsSponsored(insMedia.getIsSponsored());
            insMediaDetail.setVideoViewCount(insMedia.getVideoViewCount());
            insMediaDetail.setCaption(insMedia.getCaption());
            insMediaDetail.setCommentCount(insMedia.getCommentCount());
            insMediaDetail.setLikeCount(insMedia.getLikeCount());
            insMediaDetail.setTakenTime(insMedia.getTakenTime());
            insMediaDetail.setTypename(insMedia.getTypename());
            insMediaDetail.setLocationId(insMedia.getLocationId());
            insMediaDetail.setLocationName(insMedia.getLocationName());
            insMediaDetail.setEr(insMedia.getEr());
            insMediaDetail.setScore(insMedia.getScore());

            List<InsBlogger> insBloggers = insRelMediaTaggerUserRepository.findByShortcode(insMediaDetail.getShortcode());

            for (int i = 0; i < insBloggers.size(); i++) {
                InsAdMediaBrand insAdMediaBrand = new InsAdMediaBrand();
                insAdMediaBrand.setUid(insBloggers.get(i).getUid());
                insAdMediaBrand.setUsername(insBloggers.get(i).getUsername());
                insAdMediaBrand.setPicUrl(insBloggers.get(i).getPicUrl());
                insAdMediaBrand.setFullName(insBloggers.get(i).getFullName());
                insAdMediaBrand.setIsBusiness(insBloggers.get(i).getIsBusiness());
                insAdMediaBrand.setBusiness(insBloggers.get(i).getIsBusiness());
                insAdMediaBrand.setCategoryName(insBloggers.get(i).getCategoryName());
                if(null == insMediaDetail.getTaggedBloggers()){
                    insMediaDetail.setTaggedBloggers(new ArrayList<>(insBloggers.size()));
                }

                insMediaDetail.getTaggedBloggers().add(insAdMediaBrand);
            }

            // 时间区间
            long timeRang = System.currentTimeMillis() / 1000 - insConfig.getLatestDays() * 24 * 3600;
            // 博主信息
            InsAdBloggerInfo insAdBloggerInfo = insMediaRepository.findInsAdBloggerInfoByUid(insMediaDetail.getOwnerUid(),timeRang);
            insMediaDetail.setInsBloggerInfo(insAdBloggerInfo);

            //标签
            insMediaDetail.setTags(insMediaRepository.findInsMediaTags(id));

            // 作品百分比
            InsMediaInfoRate insMediaInfoRate = new InsMediaInfoRate();
            insMediaInfoRate.setLikeRate(insMediaDetail.getLikeCount()/(insAdBloggerInfo.getFollowerCount()+0.0));
            insMediaInfoRate.setReviewRate(insMediaDetail.getCommentCount()/(insAdBloggerInfo.getFollowerCount()+0.0));
            insMediaInfoRate.setViewRate(insMediaDetail.getVideoViewCount()/(insAdBloggerInfo.getFollowerCount()+0.0));
            insMediaInfoRate.setEr(insMediaDetail.getEr());
            insMediaDetail.setPostPerformance(insMediaInfoRate);

            // 同量级
            InsMediaInfoRate levePostPerformance = insMediaRepository.findInsMediaInfoRateByLevel(insAdBloggerInfo.getFollowerCount(),insAdBloggerInfo.getOverallCategoryName());
            insMediaDetail.setLevelPostPerformance(levePostPerformance);
        }
        return insMediaDetail;
    }

    /**
     * 根据uid 获取帖子趋势信息
     * @param uid
     * @return
     */
    public InsMediaTrendResponse getMediaTrend(long uid,int dayType){
        InsMediaTrendResponse insMediaTrendResponse = new InsMediaTrendResponse();
        // 获取30天内播主的非gtv帖子
        List<InsMedia> insMediaList = insMediaRepository.findByOwnerUidAndTakenTime(uid,
                System.currentTimeMillis() / 1000 - DAY_TYPE[dayType] * 24 * 3600);
        // 填充dto
        if(insMediaList != null && !insMediaList.isEmpty()){
            List<Double> er = new ArrayList<>(insMediaList.size());
            List<Long> like = new ArrayList<>(insMediaList.size());
            List<Integer> commentCount = new ArrayList<>(insMediaList.size());
            List<InsMediaBaseInfo> insMediaBaseInfos = new ArrayList<>(insMediaList.size());
            insMediaTrendResponse.setMinEr(99999);
            insMediaTrendResponse.setMinLike(9999999999L);
            insMediaTrendResponse.setMinCommentCount(Integer.MAX_VALUE);

            for(InsMedia insMedia : insMediaList){
                if(insMedia != null){
                    er.add(insMedia.getEr());
                    like.add(insMedia.getLikeCount());
                    commentCount.add(insMedia.getCommentCount());
                    if(insMediaTrendResponse.getMaxEr() < insMedia.getEr()){
                        insMediaTrendResponse.setMaxEr(insMedia.getEr());
                    }
                    if(insMediaTrendResponse.getMinEr() > insMedia.getEr()){
                        insMediaTrendResponse.setMinEr(insMedia.getEr());
                    }
                    if(insMediaTrendResponse.getMaxLike() < insMedia.getLikeCount()){
                        insMediaTrendResponse.setMaxLike(insMedia.getLikeCount());
                    }
                    if(insMediaTrendResponse.getMinLike() > insMedia.getLikeCount()){
                        insMediaTrendResponse.setMinLike(insMedia.getLikeCount());
                    }
                    insMediaTrendResponse.setAvgLike(insMediaTrendResponse.getAvgLike() + insMedia.getLikeCount());

                    if(insMediaTrendResponse.getMaxCommentCount() < insMedia.getCommentCount()){
                        insMediaTrendResponse.setMaxCommentCount(insMedia.getCommentCount());
                    }
                    if(insMediaTrendResponse.getMinCommentCount() > insMedia.getCommentCount()){
                        insMediaTrendResponse.setMinCommentCount(insMedia.getCommentCount());
                    }
                    insMediaTrendResponse.setAvgCommentCount(insMediaTrendResponse.getAvgCommentCount() + insMedia.getCommentCount());
                    InsMediaBaseInfo insMediaBaseInfo = new InsMediaBaseInfo();
                    insMediaBaseInfo.setDisplayUrl(insMedia.getDisplayUrl());
                    insMediaBaseInfo.setShortcode(insMedia.getShortcode());
                    insMediaBaseInfo.setTakenTime(insMedia.getTakenTime());
                    insMediaBaseInfo.setCaption(insMedia.getCaption());
                    insMediaBaseInfos.add(insMediaBaseInfo);
                }
            }
            if(!insMediaBaseInfos.isEmpty() && insMediaBaseInfos.size() > insConfig.getMediaTrendMaxCount()){
                int size = insMediaBaseInfos.size();
                insMediaTrendResponse.setEr(er.subList(size - insConfig.getMediaTrendMaxCount(),size));
                insMediaTrendResponse.setLike(like.subList(size - insConfig.getMediaTrendMaxCount(),size));
                insMediaTrendResponse.setCommentCount(commentCount.subList(size - insConfig.getMediaTrendMaxCount(),size));
                insMediaTrendResponse.setMediaInfo(insMediaBaseInfos.subList(size - insConfig.getMediaTrendMaxCount(),size));
            }else{
                insMediaTrendResponse.setEr(er);
                insMediaTrendResponse.setLike(like);
                insMediaTrendResponse.setCommentCount(commentCount);
                insMediaTrendResponse.setMediaInfo(insMediaBaseInfos);
            }

            if(!like.isEmpty()){
                insMediaTrendResponse.setAvgLike(insMediaTrendResponse.getAvgLike() / like.size());
            }
            if(!commentCount.isEmpty()){
                insMediaTrendResponse.setAvgCommentCount(insMediaTrendResponse.getAvgCommentCount() / commentCount.size());
            }

            // 同分类同量级
            val opt = insMediaRepository.findSaneCfsMediaAvgErByUid(uid);
            if(opt.isPresent()){
                InsBloggerCfsData insBloggerCfsData = opt.get();
                if(insBloggerCfsData.getExceed() != null){
                    insMediaTrendResponse.setExceedEr(insBloggerCfsData.getExceed() >= 100 ? 99.9 : insBloggerCfsData.getExceed());
                }
                if(insBloggerCfsData.getSameCfsRate() != null){
                    insMediaTrendResponse.setSameSizeEr(insBloggerCfsData.getSameCfsRate());
                }
                if(insBloggerCfsData.getRate() != null){
                    insMediaTrendResponse.setAvgEr(insBloggerCfsData.getRate());
                    if(insBloggerCfsData.getRate() != null && insBloggerCfsData.getRate() == 0){
                        insMediaTrendResponse.setExceedEr(0);
                    }
                }
            }
        }
        return insMediaTrendResponse;
    }

    /**
     * 广告得分
     * @param uid
     * @return
     */
    public InsAdMediaGoalResponse getAdGoal(long uid){
        InsAdMediaGoalResponse insAdMediaGoalResponse;
        val adMediaGoal = insMediaRepository.findAdMediaGoalByOwnerUid(uid);
        if(adMediaGoal.isEmpty()){
            insAdMediaGoalResponse = new InsAdMediaGoalResponse();
        }else {
            insAdMediaGoalResponse = adMediaGoal.get();
            if(insAdMediaGoalResponse.getAdMediaEr() != null && insAdMediaGoalResponse.getAdMediaEr() != 0){
                val opt = insMediaRepository.findSaneCfsAdMediaAvgErByUid(uid);
                if(opt.isPresent()){
                    InsBloggerCfsData insBloggerCfsData = opt.get();
                    if(insBloggerCfsData.getExceed() != null){
                        insAdMediaGoalResponse.setExceed(insBloggerCfsData.getExceed() >= 100 ? 99.9 : insBloggerCfsData.getExceed());
                    }
                    if(insBloggerCfsData.getSameCfsRate() != null){
                        insAdMediaGoalResponse.setSameSizeErRate(insBloggerCfsData.getSameCfsRate());
                    }
                    if(insBloggerCfsData.getRate() != null && insBloggerCfsData.getRate() == 0){
                        insAdMediaGoalResponse.setExceed(0.0);
                    }
                }
            }
        }

        return insAdMediaGoalResponse;
    }

    /**
     * 查询广告帖子标记品牌分类信息
     * @param uid
     * @return
     */
    public InsAdMediaBrandCategoryResponse getAdTagBrandCategory(long uid){
        List<InsAdMediaBrandCategory> insAdMediaBrandCategories = insMediaRepository.findAdMediaBrandCategoryByUid(uid,
                System.currentTimeMillis() / 1000 - insConfig.getLatestDays() * 24 * 3600);
        InsAdMediaBrandCategoryResponse insAdMediaBrandCategoryResponse = new InsAdMediaBrandCategoryResponse();
        int sum = 0;
        InsAdMediaBrandCategory insAdMediaBrandCategory;
        if(insAdMediaBrandCategories != null && !insAdMediaBrandCategories.isEmpty()){
            Iterator<InsAdMediaBrandCategory> iterator =  insAdMediaBrandCategories.iterator();
            while(iterator.hasNext()){
                insAdMediaBrandCategory = iterator.next();
                if(insAdMediaBrandCategory != null){
                    sum += insAdMediaBrandCategory.getBrandCount();
                }
                if(StringUtils.isEmpty(insAdMediaBrandCategory.getCategoryName())){
                    iterator.remove();
                }
            }
        }
        insAdMediaBrandCategoryResponse.setBrandSumCount(sum);
        insAdMediaBrandCategoryResponse.setBrandCategory(insAdMediaBrandCategories);
        return insAdMediaBrandCategoryResponse;
    }

    /**
     * 根据uid 查询广告帖子标记品牌分页信息
     * @param uid
     * @param category
     * @param page
     * @param size
     * @return
     */
    public Page<InsAdMediaBrand> getAdTagBrand(long uid,String category, int page,int size){
        size = size > 0 ? size : 10;
        return insMediaRepository.findAdMediaBrandByUid(uid,
                System.currentTimeMillis() / 1000 - insConfig.getLatestDays() * 24 * 3600, category,page,size);
    }

    /**
     * 根据uid 标记品牌帖子分类信息
     * @param uid
     * @return
     */
    public InsAdMediaBrandCategoryResponse getAdTagBrandMediaCategory(long uid){
        long limitTime = System.currentTimeMillis() / 1000 - insConfig.getLatestDays() * 24 * 3600;
        List<InsAdMediaBrandCategory> insAdMediaBrandCategories = insMediaRepository.findAdTagBrandMediaCategoryByUid(uid,limitTime);
        InsAdMediaBrandCategoryResponse insAdMediaBrandCategoryResponse = new InsAdMediaBrandCategoryResponse();
        InsAdMediaBrandCategory insAdMediaBrandCategory;
        if(insAdMediaBrandCategories != null && !insAdMediaBrandCategories.isEmpty()){
            Iterator<InsAdMediaBrandCategory> iterator =  insAdMediaBrandCategories.iterator();
            while(iterator.hasNext()){
                insAdMediaBrandCategory = iterator.next();
                if(StringUtils.isEmpty(insAdMediaBrandCategory.getCategoryName())){
                    iterator.remove();
                }
            }
        }
        int sum = insMediaRepository.findAdTagBrandMediaCategoryTotalByUid(uid,limitTime);
        insAdMediaBrandCategoryResponse.setBrandSumCount(sum);
        insAdMediaBrandCategoryResponse.setBrandCategory(insAdMediaBrandCategories);
        return insAdMediaBrandCategoryResponse;
    }

    /**
     * 根据uid 查询广告帖子标记品牌分页信息
     * @param uid
     * @param category
     * @param orderType
     * @param page
     * @param size
     * @return
     */
    public Page<InsAdTagBrandMedia> getAdTagBrandMedia(long uid,String category, int orderType,int page,int size){
        String order = orderType == 1 ? "t3.taken_time" : "t3.er";
        size = size > 0 ? size : 10;
        return insMediaRepository.findAdTagBrandMediaByUid(uid,
                System.currentTimeMillis() / 1000 - insConfig.getLatestDays() * 24 * 3600,category,order,page,size);
    }

    /**
     * 获取播主帖子信息
     * @param uid
     * @return
     */
    public InsBloggerMediaInfo getInsBloggerMediaInfo(long uid,int dayType){
        val insBloggerMediaInfo = insMediaRepository.findBloggerMediaInfoByOwnerUid(uid,
                System.currentTimeMillis() / 1000 - DAY_TYPE[dayType] * 24 * 3600);
        if(insBloggerMediaInfo.isEmpty()){
            return new InsBloggerMediaInfo();
        }
        return insBloggerMediaInfo.get();

    }

    /**
     * 根据uid 以及限制时间 获取 账户发文时间统计数据
     * @param uid
     * @return
     */
    public InsMediaTakenTimeResponse getInsMediaTakenTimeInfoByUid(long uid,int dayType){
        InsMediaTakenTimeResponse insMediaTakenTimeResponse = new InsMediaTakenTimeResponse();
        long limitTime = System.currentTimeMillis() / 1000 - DAY_TYPE[dayType] * 24 * 3600;
        val insMediaTakenTimeList = insMediaRepository.findInsMediaTakenTimeInfoByUid(uid,limitTime);
        InsMediaTakenTime topInsMediaTakenTime = new InsMediaTakenTime();
        if(insMediaTakenTimeList != null && !insMediaTakenTimeList.isEmpty()){
            double maxEr = -1;
            for(InsMediaTakenTime insMediaTakenTime : insMediaTakenTimeList){
                if(insMediaTakenTime != null && insMediaTakenTime.getPostWeek() != null && insMediaTakenTime.getPostHour() != null){
                    int day = insMediaTakenTime.getPostWeek() > 0 ? insMediaTakenTime.getPostWeek() - 1 : 6;
                    insMediaTakenTime.setPostWeek(day);
                    insMediaTakenTimeResponse.getInsMediaTakenTime()[day][insMediaTakenTime.getPostHour()] = insMediaTakenTime;
                    if(insMediaTakenTime.getAvgEr() != null && insMediaTakenTime.getAvgEr() > maxEr){
                        maxEr = insMediaTakenTime.getAvgEr();
                        topInsMediaTakenTime = insMediaTakenTime;
                    }
                }
            }
        }
        insMediaTakenTimeResponse.setTopInsMediaTakenTime(topInsMediaTakenTime);
        return insMediaTakenTimeResponse;
    }

    /**
     * 获取博主的帖子列表
     * @param uid
     * @param page
     * @param pageSize
     * @param mediaType
     * @param dayType
     * @param sort
     * @return
     */
    public Page<InsMediaInfo> getPageByUid(Long uid, int page, int pageSize, Integer mediaType,Integer sponsored,Integer business,Integer product, int dayType, int sort){
        return insMediaRepository.findPageByUid(uid,page,pageSize,mediaType,sponsored, business, product,DateUtil.offsetDay(new Date(),-DAY_TYPE[dayType]).getTime()/1000,System.currentTimeMillis() / 1000,sort);
    }
}
